/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sita.friend.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mikhaellopez.circularimageview.CircularImageView;
import com.sita.bike.R;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.SearchResponse;
import com.sita.bike.rest.model.SearchUserRequest;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.ImageManager;
import com.sita.bike.utils.RetrofitUtils;
import com.sita.friend.ui.widget.EaseAlertDialog;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.global.LocalConstants;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class FriendAddUserActivity extends ActivityBase {
    private EditText mSearchText;
    private LinearLayout searchedUserLayout;
    private RecyclerView mSearchList;
    //    private TextView nameText, mTextView;
//    private Button searchBtn, addBtn;
//    private ImageView avatar;
    private InputMethodManager inputMethodManager;
    //    private String toAddUsername;
//    private String toAddUserId;
    private List<Account> mSearchAccounts;
    private FriendSearchListAdapter mAdapter;
    private ProgressDialog progressDialog;
    @Bind(R.id.img_back)
    public ImageView img_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_activity_add_person);
        ButterKnife.bind(this);

        mSearchText = (EditText) findViewById(R.id.edit_search_keyword);
        mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) mSearchText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    searchContact();
                    return true;
                }
                return false;
            }

        });

        mSearchList = (RecyclerView) findViewById(R.id.friend_search_list);
        mSearchList.setLayoutManager(new LinearLayoutManager(this));
        mSearchList.setAdapter(mAdapter = new FriendSearchListAdapter());
        mAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                // show the person' detail view
                Account person = mSearchAccounts.get(position);
                Intent intent = new Intent(FriendAddUserActivity.this, FriendDetailActivity.class);
                intent.putExtra(LocalConstants.BUNDLE_ACCOUNT_ID, person.mAccountId);
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        searchedUserLayout = (LinearLayout) findViewById(R.id.ll_user);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initData();
    }

    private void initData() {
        if (mSearchAccounts == null) {
            mSearchAccounts = new ArrayList<Account>();
        }
    }

    public void searchContact() {
        final String name = mSearchText.getText().toString();
        if (TextUtils.isEmpty(name)) {
            new EaseAlertDialog(this, R.string.Please_enter_a_username).show();
            return;
        }
        showProgress();
        doSearch(name);
    }

    private void doSearch(String keyword) {
        SearchUserRequest req = new SearchUserRequest();
        req.mAccountId = AccountUtils.getAccountID();
        req.mKeyword = keyword;
        req.mIncludeSelf = false;

        RestClient.getRestNormalService().search(req, new Callback<SearchResponse>() {
            @Override
            public void success(SearchResponse searchResponse, Response response) {
                if (response.getStatus() == 200 &&
                        searchResponse.mErrorCode.equals("0") &&
                        searchResponse.mData.size() != 0) {

                    if (mSearchAccounts == null) {
                        mSearchAccounts = new ArrayList<Account>();
                    }
                    mSearchAccounts.clear();
                    mSearchAccounts.addAll(searchResponse.mData);
                    mAdapter.notifyDataSetChanged();

                    searchedUserLayout.setVisibility(View.VISIBLE);

                } else if (searchResponse.mData.size() == 0) {
                    Toast.makeText(FriendAddUserActivity.this, getResources().getText(R.string.friend_search_no_result), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(FriendAddUserActivity.this, getResources().getText(R.string.friend_search_fail) + searchResponse.mErrorCode, Toast.LENGTH_SHORT).show();
                }

                progressDialog.dismiss();
            }

            @Override
            public void failure(RetrofitError error) {
                RetrofitUtils.displayError(FriendAddUserActivity.this, error);
                progressDialog.dismiss();
            }
        });
    }

    public void back(View v) {
        finish();
    }

    private void showProgress() {
        progressDialog = new ProgressDialog(this);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    @OnClick(R.id.img_back)
    public void back() {
        this.finish();
    }

    class FriendSearchListViewHolder extends RecyclerView.ViewHolder {
        private CircularImageView mHeaderView;
        private TextView mName;

        public FriendSearchListViewHolder(View itemView) {
            super(itemView);
            mHeaderView = (CircularImageView) itemView.findViewById(R.id.friend_search_item_avatar);
            mName = (TextView) itemView.findViewById(R.id.friend_search_item_name);
        }
    }

    interface OnItemClickLitener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    class FriendSearchListAdapter extends RecyclerView.Adapter<FriendSearchListViewHolder> {


        private OnItemClickLitener mOnItemClickLitener;

        public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
            this.mOnItemClickLitener = mOnItemClickLitener;
        }

        public FriendSearchListAdapter() {
        }

        @Override
        public int getItemCount() {
            return mSearchAccounts.size();
        }

        @Override
        public FriendSearchListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            FriendSearchListViewHolder viewHolder = new FriendSearchListViewHolder(LayoutInflater.from(FriendAddUserActivity.this)
                    .inflate(R.layout.friend_search_list_tem, parent, false));
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final FriendSearchListViewHolder holder, int position) {
            String name = TextUtils.isEmpty(mSearchAccounts.get(position).mNickName) ? mSearchAccounts.get(position).mMobile :
                    mSearchAccounts.get(position).mNickName;
            holder.mName.setText(name);
            ImageManager.loadImage(holder.mHeaderView, mSearchAccounts.get(position).mAvatar);

            if (mOnItemClickLitener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getLayoutPosition();
                        mOnItemClickLitener.onItemClick(holder.itemView, pos);
                    }
                });

                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = holder.getLayoutPosition();
                        mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                        return false;
                    }
                });
            }

        }
    }

}
